<?php
namespace App\Goods\Services;

use App\BaseService;
use App\Goods\Models\CommonName;
use App\Goods\Models\GoodsAttr;
use App\Exceptions\GoodsException;
use Exception;

class GoodsAttrService extends BaseService
{

    /**
     *
     * @param $params
     * @return mixed
     * @throws \Exception
     */
    public function attrList($params)
    {
        return GoodsAttr::select(['id', 'sort', 'name', 'pid', 'type'])->where(function ($table) use ($params){
            if(!empty($params['belongs'])){
                $table->where('belongs', strtoupper($params['belongs']));
            }
        })->orderBy('sort', 'asc')->get();
    }

    /**
     * 属性添加
     * @param $params
     * @return mixed
     * @throws Exception
     */
    public function attrAdd($params){

        $createData= [
            'name' => $params['name'],
            'type' => isset($params['type']) ? $params['type'] : 1,
            'sort' => isset($params['sort']) ? $params['sort'] : 0,
            'default' => isset($params['default']) ? $params['default'] : '',
            'belongs' => isset($params['belongs']) && $params['belongs'] == 'SUP' ? 'SUP' : 'SKU'
        ];
        $goodsAttrModels = new GoodsAttr();
        $info = $goodsAttrModels->create($createData);
        if (!$info){
            throw new Exception('属性添加失败！');
        }
        return $info;
    }

    //属性修改
    public function attrEdit($params){
        $where= [
            'id' =>$params['id']
        ];
        $updateData= [
            'name' => $params['name'],
            'type' => $params['type'],
            'sort' => $params['sort'],
            'radio' => $params['radio'],
            'belongs' => $params['belongs']
        ];
        $goodsArrModels =new GoodsAttr();
        $info= $goodsArrModels->where($where)->Update($updateData);
        if ($info  == null){
            throw new \Exception('属性修改失败！');
        }
        return $info;
    }
}
